import React, {useEffect, useState} from 'react';
import { Space, Table, Tag,Popconfirm,Card,Form,Input,Select,DatePicker,Pagination  } from 'antd';
import type { TableProps,PaginationProps } from 'antd';
import SearchForm from './SearchForm';
import EditForm from './EditForm';
import SubDetails from './subDetails'
import request from "@/api/index";
import './index.less'
import {ResponseType} from "@/api/indexType";
import {setUserOptions,setSubAllOptions} from "@/redux/modules/subModule/action";
import {connect} from "react-redux";
import { ColumnType , columnDataType} from './data'
import dayjs from "dayjs";

const { Column } = Table;
const { RangePicker } = DatePicker;

function SubIndex(props) {
    let subList =  [
        { value: '1', label: '月度' },
        { value: '2', label: '季度' },
        { value: '3', label: '年度' },
        { value: '4', label: '自定义' },
    ]
    let dateFormat='YYYY-MM-DD HH:mm:ss'
    let rePageInfo = {
        current:1,
        pageSize:2,
        total:0,
    }
    let {setUserOptions,setSubAllOptions} = props
    const [rowData, setRowData] = useState<columnDataType>({
        subId:'',
        username:'',
        uid:'',
        phoneNum:'',
        email:'',
        subscripte_type:'',
        subType:'',
        bqMoney:0,
        subNum:0,
        startDate:new Date(),
        endDate:new Date(),
    });
    const [editModal, setEditModal] = useState(false);
    const [modalTitle, setModalTitle] = useState('');
    const [type, setType] = useState('');
    const [loading, setLoading] = useState(false);
    const [searchData, setSearchData] = useState({});
    const [pageInfo, setPageInfo] = useState(rePageInfo);
    const [data, setData] = useState<ColumnType[]>([]);
    const [subAllData, setSubAllData] = useState([]);
    const [orderData, setOrderData] = useState({
        field:"endDate",
        order:"desc"
    });

    //订阅详情数据
    const [subDetailModal, setSubDetailModal] = useState(false);
    const [subDetailData, setSubDetailData] = useState([]);
    useEffect(()=>{
        getAllUser()
        getAllSub()
        toQuery({
            ...searchData,
            ...orderData,
            page:pageInfo.current,
            pageSize:pageInfo.pageSize,
        })
    },[])
    const getAllSub = () => {
        request.get({
            url:'/subInfo/list',
            data:{
                ...data,
                page:1,
                pageSize:999,
            },
        }).then((res:ResponseType)=>{
            let data = res.data || []
            let list = []
            if(data && data.length>0){
                list = data.map((item)=>{
                    return{
                        ...item,
                        value:item._id,
                        label:item.subName,
                    }
                })
            }
            setSubAllData(list)
            setSubAllOptions(list)
        })
    }
    const getAllUser = () => {
        request.get({
            url:"/subUser/list",
            data:{
                page:1,
                pageSize:999,
            },
        }).then((res:ResponseType)=>{
            let data = res.data || []
            let list = []
            if(data && data.length>0){
                list = data.map((item)=>{
                    return{
                        ...item,
                        value:item.uid,
                        label:item.username,
                    }
                })
            }
            setUserOptions(list)
        })
    }
    const toSearch = (data) => {
        setSearchData(data)
        toQuery(data)
    }
    const toQuery = (data) => {
        console.log('pageInfo',pageInfo)
        setLoading(true)
        let params = {...data,...orderData}
        if(params.startDate){
            params.startDate =  dayjs(params.startDate).startOf('day').format(dateFormat)
        }
        if(params.endDate){
            params.endDate =  dayjs(params.endDate).endOf('day').format(dateFormat)
        }
        request.post({
            url:"/sub/list",
            data:{
                ...params,
                page:pageInfo.current,
                pageSize:pageInfo.pageSize,
            },
        }).then((res:ResponseType)=>{
            let {data, currentPage,pageSize,total} = res
            let list = data.map((item,index)=>{
                return{
                    ...item,
                    "key":item._id+'_'+index,
                }
            })
            setData(list)
            setPageInfo({
                ...pageInfo,
                total:total,
            })
        }).finally(()=>{
            setLoading(false)
        })
    }
    const addUser = (data) => {
        setRowData({
            subId:'',
            username:'',
            uid:'',
            phoneNum:'',
            email:'',
            subscripte_type:'',
            subType:'',
            bqMoney:0,
            subNum:0,
            startDate:new Date(),
            endDate:new Date(),
        })
        setType('add')
        setModalTitle('新增')
        setEditModal(true)
    }
    const edit = (record) => {
        setRowData(record)
        setType('edit')
        setModalTitle('编辑')
        setEditModal(true)
    }
    const lookDetail = (record) => {
        setRowData(record)
        setType('look')
        setModalTitle('详情')
        setEditModal(true)
    }
    const modalOk = (val) => {
        if(type === 'add'){
            toAdd(val)
        }else if(type === 'edit'){
            toEdit(val)
        }
        setEditModal(false)
    }
    const toAdd = (val) => {
        setLoading(true)
        request.post({
            url:"/sub/addSub",
            data:{
                ...val,
                startDate:dayjs(val.startDate).format('YYYY-MM-DD HH:mm:ss'),
                endDate:dayjs(val.endDate).format('YYYY-MM-DD HH:mm:ss'),
            },
        }).then((res:ResponseType)=>{
            setPageInfo(rePageInfo)
            toQuery({...searchData,...orderData})
        }).finally(()=>{
            setLoading(false)
        })
    }
    const toEdit = (val) => {
        setLoading(true)
        request.post({
            url:"/sub/editSub",
            data:{
                'subId':rowData.subId,
                ...val,
            },
        }).then((res:ResponseType)=>{
            setPageInfo(rePageInfo)
            toQuery({...searchData,...orderData})
        }).finally(()=>{
            setLoading(false)
        })
    }
    const modalCancel = () => {
        setEditModal(false)
    }
    const toRemove = (record) => {
        setLoading(true)
        request.post({
            url:"/sub/delSub",
            data:{
                subId:record.subId
            },
        }).then((res:ResponseType)=>{
            setPageInfo(rePageInfo)
            toQuery({...searchData,...orderData})
        }).finally(()=>{
            setLoading(false)
        })
    }
    const delCancel = () => {
        console.log('delCancel-----')
    }
    const lookSbuHistory = (record) => {
        console.log('lookSbuHistory-----',record)
    }
    const onChange = (pagination, filters, sorter, extra) => {
        // console.log('onChange-----',pagination)
        // console.log('sorter-----',sorter)
        // console.log('extra-----', extra)
        if(extra.action === 'sort'){
            setOrderData({
                field:sorter.field,
                order:sorter.order==='descend'?'desc':'asc',
            })
            toQuery({
                ...searchData,
                ...orderData
            })
        }else if(extra.action === 'paginate'){
            setPageInfo({...pagination})
            toQuery({
                ...searchData,
                ...orderData,
            })
        }
    }
    const lookSubDetails = (val) => {
        setLoading(true)
        request.post({
            url:"/sub/subDetailByUid",
            data:{
                uid:val.uid
            },
        }).then((res:ResponseType)=>{
            let list = res.data.map(item=>{
                return {
                    ...item,
                    key:item._id,
                }
            })
            setSubDetailData(list)
            setSubDetailModal(true)
        }).finally(()=>{
            setLoading(false)
        })
    }
    const subDetailCancel = () => {
        setSubDetailModal(false)
    }
    const getSubType = (val) => {
        let str = ''
        let curData = subList.filter(item=>item.value === val.subType)
        if(curData.length>0){
            str = curData[0].label
        }
        return str
    }
    return (
        <div>
            <Card className="mt16">
                <SearchForm
                    subList={subList}
                    add={addUser}
                    toQuery={toSearch}
                />
            </Card>
            <Card className="mt16">
                <Table dataSource={data} onChange={onChange} pagination={pageInfo}>
                    <Column title="用户名" dataIndex="username" key="username" />
                    <Column title="手机号" dataIndex="phoneNum" key="phoneNum" render={(text, record) =>
                        <span>{text==''?'暂无':text}</span>
                    }/>
                    <Column title="邮箱" dataIndex="email" key="email" />
                    <Column title="订阅类型" dataIndex="subscripte_type" key="subscripte_type"  render={(text, record) =>
                        <span>{getSubType(record)}</span>
                    }/>
                    <Column title="内存" dataIndex="subRAM" key="subRAM"  render={(text, record) =>
                        <span>{text}G</span>
                    }/>
                    <Column title="本期付费金额" dataIndex="bqMoney" key="bqMoney" sorter render={(text, record) =>
                        <span>{text}元</span>
                    }/>
                    <Column title="订阅次数" dataIndex="subNum" key="subNum" sorter/>
                    <Column title="开始时间" dataIndex="startDate" key="startDate"
                            render={(text, record) =>
                                <span>{dayjs(text).format(dateFormat)}</span>
                            }/>
                    <Column title="到期时间" dataIndex="endDate" key="endDate" sorter
                            render={(text, record) =>
                                <span>{dayjs(text).format(dateFormat)}</span>
                            }/>
                    <Column title="状态" dataIndex="subStatus" key="subStatus"  render={(text, record) =>(
                        text==0
                            ?<Tag color="success">正常</Tag>
                            :<Tag color="error">过期</Tag>
                    )}/>
                    <Column
                        title="操作"
                        key="operation"
                        render={(text, record:ColumnType) => (
                            <Space>
                                {
                                    record.subStatus === 0
                                    ?<a onClick={() => edit(record)}>编辑</a>
                                    :<a onClick={() => lookDetail(record)}>查看</a>
                                }
                                <Popconfirm
                                    title="确定要删除此条数据吗"
                                    description=""
                                    onConfirm={()=>toRemove(record)}
                                    onCancel={delCancel}
                                    okText="是"
                                    cancelText="否"
                                >
                                    <a className="delBtn">删除</a>
                                </Popconfirm>
                                <a onClick={() => lookSubDetails(record)}>订阅记录</a>
                            </Space>
                        )}
                    />
                </Table>
            </Card>
            {
                editModal
                    ?<EditForm
                        modalShow={editModal}
                        title={modalTitle}
                        componentDisabled={type==='look'}
                        modalOk={modalOk}
                        modalCancel={modalCancel}
                        data={rowData}
                    />
                    :''
            }
            {
                subDetailModal
                    ?<SubDetails
                        modalShow={subDetailModal}
                        modalCancel={subDetailCancel}
                        tableData={subDetailData}
                    />
                    :''
            }
        </div>
    );
}

const mapStateToProps = (state:any)=> {
    return{
        subOptions:state.subData.subOptions,
        userOptions:state.subData.userOptions,
    }
}
const mapDispatchToProps = {setUserOptions,setSubAllOptions}
export default connect(null,mapDispatchToProps)(SubIndex);
